<?php
/**
 * 宝箱类
 * 
 * Created	: 2011-05-18
 * Modified : 2011-05-18
 * @author  : 陈立强
 */
class TreasureBox
{
	
	public static $cfg  = null;
	public static $cfgName = 'item/treasure_box';
	
	/**
	 * 获取得宝箱
	 * @param int $uid 
	 * @param int $item_id 宝箱物品ID
	 * @param int $lvl 宝箱等级
	 */
	public static function get($uid, $item_id, $lvl, $class=null, $mailContents='')
	{
		global $DB, $L, $G;
		
		$cfgList = C('item/treasure_box');
		if (!isset($cfgList[$item_id])) {
			return array(
				'val' => false,
				'msg' => $L,
			);
		}
		$cfgInfo = $cfgList[$item_id];
		
		if ($class) {
			$attr = 'class='.$class;
		} else {
			$attr = '';
		}
		
		// 获取奖励类型
		$data = array(
			'item_id'	=> $item_id,
			'item_type'	=> $cfgInfo['item_type'],
			'title'		=> $cfgInfo['title'],
			'num'		=> 1,
			'quality'	=> 0,
			'stack'		=> 0,
			'lvl'		=> $lvl,
			'color'		=> 0,
			'part'		=> 0,
			'staff_id'	=> 0,
			'status'	=> 1,
			'strengthen_lvl'	=> 0,
			'inlay'		=> '',
			'attr'		=> $attr,
		);
		$ret = Bag::in($uid, $data);
		$inMail = false;
		// 背包空间不足,邮件发送
		if (!$ret && Bag::$msg == $L['not_enough_grid_in_bag']) {
			if (empty($mailContents)) {
				$content = sprintf($L['congratulation_to_get_treasurebox'], $cfgInfo['title']);
			} else {
				$content = $mailContents;
			}
			$attach = array(
				array(
					'item_id'	=> $item_id,
					'lvl'		=> $lvl,
					'attr'		=> $attr
				)
			);
			$to_nickname = User::getNickname($uid);
			$ret = Mail::send(0, $to_nickname, $content, 1, $attach);
			if ($ret['val']) {
				$ret = true;
			} else {
				$ret = $ret['val'];
				$result['msg'] = $ret['msg'];
			}
			$inMail = true;
		}
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$result['data']['in_mail'] = $inMail;
		} else {
			if (isset($result['msg'])) {
				$result['msg'] = $L['Failure_Update'];
			}
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('treasurebox_get', $str);
		}
		
		return $result;
	}
	
	/**
	 * 开启宝箱
	 * @param $uid
	 * @param $bag_id
	 */
	public static function open($uid, $bag_id)
	{
		global $DB, $L, $G;
		
		$sql = 'SELECT * FROM bag WHERE bag_id='.$bag_id;
		$itemInfo = $DB->getValue($sql);
		if (!$itemInfo || $itemInfo['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$DB->beginTransaction();
		
		$cfgList = C('item/treasure_box');
		$cfgInfo = $cfgList[$itemInfo['item_id']];
		$sign = getRandResult($cfgInfo['rate_list'], array_sum($cfgInfo['rate_list']));
//		$sign = 'coin';
		$attr = json_decode($itemInfo['attr'], true);
		$DB->setTransactionState(false);
		$title = '';
		$num = 1;
		switch ($sign) {
			case 'coin':
				if ($itemInfo['item_id'] == 11006) {
					$num = rand($cfgInfo['item_list']['coin'][0], $cfgInfo['item_list']['coin'][1]);
				} else {
					$num = $cfgInfo['item_list']['coin'] * $itemInfo['lvl'];
				}
				$sql = 'UPDATE user SET coin=coin+'.$num.' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
				$itemCfgList = C('item/other');
				$title = $itemCfgList[65535]['title'];
				break;
				
			case 'ticket':
				$num = $cfgInfo['item_list']['ticket'] ;
				$sql = 'UPDATE user SET ticket=ticket+'.$num.' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
				$itemCfgList = C('item/other');
				$title = $itemCfgList[65534]['title'];
				break;
				
			case 'exp':
				if ($itemInfo['item_id'] == 11006) {
					$num = rand($cfgInfo['item_list']['exp'][0], $cfgInfo['item_list']['exp'][1]);
				} else {
					$num = $cfgInfo['item_list']['exp'] * $itemInfo['lvl'];
				}
				$sql = 'UPDATE user SET exp=exp+'.$num.' WHERE uid='.$uid;
				$ret = $DB->exeSql($sql);
				$itemCfgList = C('item/other');
				$title = $itemCfgList[65532]['title'];
				break;
			
			case 'sec_mat':
				CI_ONCE('build/making');
				$classSign = $G['make_class_type_sign_list'][$attr['class']];
				// 只能对应制造类型下取辅材
				$mat_item_id = array_rand($G[$classSign.'_sec_mat_item']);
				$secMat = $G[$classSign.'_sec_mat_item'][$mat_item_id];
				$quality = $cfgInfo['item_list']['sec_mat']['quality'];
				$num = $cfgInfo['item_list']['sec_mat']['num'];
				$data = array(
					'uid'		=> $uid,
					'item_id'	=> $mat_item_id,
					'item_type'	=> $secMat['item_type'],
					'title'		=> $secMat['title'].$G['id_star'][$quality],
					'num'		=> $num,
					'quality'	=> $quality,
					'stack'		=> 1,
					'lvl'		=> 0,
				);
				$ret = Depot::in($uid, $data);
				if (!$ret['val']) {
					$result['msg'] = $ret['msg'];
				}
				$ret = $ret['val'];
				$title = $secMat['title'];
				break;
			
			case 'gem':
				$gemList = C('item/gem');
				// 只能取对应制造类型的宝石
				foreach ($gemList as $item_id => $gem) {
					if ($gem['class'] == $attr['class']) {
						break;
					}
				}
				$key = array_rand($gem['add_attr_type']);
				$abi_id = $gem['add_attr_type'][$key];
				$abi_val = $G['gem_lvl_val'][$itemInfo['lvl']];
				$attr = '{"'.$abi_id.'":"'.$abi_val.'"}';
				$data = array(
					'uid'		=> $uid,
					'item_id'	=> $item_id,
					'item_type'	=> $gem['item_type'],
					'title'		=> $gem['title'],
					'num'		=> 1,
					'quality'	=> 0,
					'stack'		=> 0,
					'lvl'		=> $itemInfo['lvl'],
					'color'		=> $gem['color'],
					'part'		=> 0,
					'staff_id'	=> 0,
					'status'	=> 1,
					'strengthen_lvl'	=> 0,
					'inlay'		=> '',
					'attr'		=> $attr,
				);
				$ret = Bag::in($uid, $data);
				if ($ret) {
					$bag_id = $ret;
				} else {
					$result['msg'] = Bag::$msg;
				}
				$title = $gem['title'];
				break;
			
			case 'equip':
				$attr = json_decode($itemInfo['attr'], true);
				$classSign = $G['make_class_type_sign_list'][$attr['class']];
				$equipCfgList = C('item/equip');
				$tmp = array();
				foreach ($equipCfgList as $item_id=>$cfg) {
					if ($cfg['class'] != $attr['class']) {
						continue;
					}
					if ($cfg['lvl'] != $itemInfo['lvl']) {
						continue;
					}
					$tmp[$item_id] = $cfg;
				}
				$item_id = array_rand($tmp);
				$equipCfg = $tmp[$item_id];
				$color = $cfgInfo['item_list']['equip'];
				$colorSign = $G['id_color'][$color];
				$subTypeList = $G[$classSign];
				// 根据装备颜色生成的宝石槽个数
				$inlay = array();
				for ($i=0; $i<$G['equip_color_slot_num'][$colorSign]; $i++) {
					$inlay[$i+1] = array();
				}
				$inlay = json_encode($inlay);
				$_attr = array();
				// 根据装备颜色确定要生成的属性个数
				for ($i=0; $i<$G['equip_color_attr_num'][$colorSign]; $i++) {
					$_k = array_rand($subTypeList);
					$_info = $subTypeList[$_k];
					unset($subTypeList[$_k]);
					$abi_id = $_info['item_id'];
					$abi_val = rand($equipCfg['add_abi'][$colorSign][0], $equipCfg['add_abi'][$colorSign][1]);
					$_attr[$abi_id] = $abi_val;
				}
				$attr = array(
					'base' => $_attr,
					'result' => $_attr,
				);
				$attr = json_encode($attr);
				$data = array(
					'uid'		=> $uid,
					'item_id'	=> $item_id,
					'item_type'	=> $equipCfg['item_type'],
					'title'		=> $equipCfg['title'],
					'num'		=> 1,
					'quality'	=> 0,
					'stack'		=> 0,
					'lvl'		=> $itemInfo['lvl'],
					'color'		=> $color,
					'part'		=> $equipCfg['part'],
					'staff_id'	=> 0,
					'status'	=> 1,
					'strengthen_lvl'	=> 0,
					'inlay'		=> $inlay,
					'attr'		=> $attr,
				);
				$ret = Bag::in($uid, $data);
				if ($ret) {
					$bag_id = $ret;
				} else {
					$result['msg'] = Bag::$msg;
				}
				$title = $equipCfg['title'];
				break;
			
			case 'card':
				$tmp = C('item/other');
				$list = array();
				foreach ($tmp as $item_id => $item) {
					if ($item['item_type'] != 54) {
						continue;
					}
					$list[$item_id] = $item;
				}
				$item_id = array_rand($list);
				$card = $list[$item_id];
				$attr = array(
					'use_times' => rand($card['use_times'][0], $card['use_times'][1])
				);
				$data = array(
					'uid'		=> $uid,
					'item_id'	=> $item_id,
					'item_type'	=> $card['item_type'],
					'title'		=> $card['title'],
					'num'		=> 1,
					'quality'	=> 0,
					'stack'		=> 0,
					'lvl'		=> 1,
					'color'		=> 0,
					'part'		=> 0,
					'staff_id'	=> 0,
					'status'	=> 1,
					'strengthen_lvl'	=> 0,
					'inlay'		=> '',
					'attr'		=> json_encode($attr),
				);
				$ret = Bag::in($uid, $data);
				if ($ret) {
					$bag_id = $ret;
				} else {
					$result['msg'] = Bag::$msg;
				}
				$title = $card['title'];
				break;
			
			case 'card_mat':
				$itemList = C('item/gift');
				$tmp = array();
				$lvl = ceil($itemInfo['lvl']/$cfgInfo['item_list']['card_mat']['lvl_param']);
				foreach ($itemList as $item_id=>$item) {
					if ($item_id < 10011 || $item_id > 10015) {
						continue;
					}
					if ($item['lvl'] == $lvl) {
						break;
					}
				}
				$num = $cfgInfo['item_list']['card_mat']['num'];
				$data = array(
					'uid'		=> $uid,
					'item_id'	=> $item_id,
					'num'		=> $num,
					'title'		=> $item['title'],
					'lvl'		=> $lvl,
				);
				$ret = PropsBox::in($uid, $data);
				if (!$ret['val']) {
					$result['msg'] = $ret['msg'];
				}
				$ret = $ret['val'];
				$title = $item['title'];
				break;
			
			default:
				$ret = false;
				break;
		}
		
		$DB->setTransactionState(true);
		
		// 宝箱开启后消失
		if ($ret) {
			$ret = $DB->delete('bag', 'bag_id='.$bag_id);
		}
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
			$result['data']['title'] = $title;
			$result['data']['num'] = $num;
//			$result['data']['sign'] = $sign;
		} else {
			$DB->rollBack();
			if (!isset($result['msg'])) {
				$result['msg'] = $L['Failure_Update'];
			}
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('treasurebox_open', $str);
		}
		
		return $result;
	}
	
	/**
	 * 分享宝箱
	 * @param int $uid
	 * @param int $bag_id
	 * @param int $friend_id
	 */
	public static function share($uid, $bag_id, $friendList)
	{
		global $DB, $L, $G;
		
		$today = strtotime('today');
		
		$sql = 'SELECT * FROM bag WHERE bag_id='.$bag_id;
		$itemInfo = $DB->getValue($sql);
		if (!$itemInfo || $itemInfo['uid'] != $uid) {
			return array(
				'val' => false,
				'msg' => $L['invalid_request']
			);
		}
		
		$cfgList = C('item/treasure_box');
		$cfgInfo = $cfgList[$itemInfo['item_id']];
		// 宝箱是否属于可分享
		if (!$cfgInfo['share']) {
			return array(
				'val' => false,
				'msg' => $L['this_box_cannot_share']
			);
		}
		
		// 当天分享次数已满
		$sql = 'SELECT share_box_times,last_share_box_time FROM user WHERE uid='.$uid;
		$user = $DB->getValue($sql);
		// 是否今日第一次进行分享
		$todayFirst = false;
		if ($user['last_share_box_time'] >= $today && $user['share_box_times'] == 0) {
			return array(
				'val' => false,
				'msg' => $L['share_times_reached_max_today']
			);
		} else if ($user['last_share_box_time'] < $today) {
			$todayFirst = true;
		}
		
		// 判断是否好友
		$where = '(uid='.$uid.' or to_uid='.$uid.') and status=1';
		$sql = 'SELECT uid,to_uid FROM user_friend WHERE '.$where;
		$list = $DB->getList($sql);
		$allFriend = array();
		foreach ($list as $v) {
			if ($v['uid'] == $uid) {
				$allFriend[] = $v['to_uid'];
			} else {
				$allFriend[] = $v['uid'];
			}
		}
		$noFriend = true;
		foreach ($friendList as $u) {
			if (!in_array($u, $allFriend)) {
				$noFriend = false;
				break;
			}
		}
		if (!$noFriend) {
			return array(
				'val' => false,
				'msg' => $L['not_friend_in_list']
			);
		}
		
		$friendIds = join(',', $friendList);
		$sql= 'SELECT uid,nickname,be_shared_box_times,last_be_shared_box_time FROM user '
				.' WHERE uid in ('.$friendIds.')';
		$friendList = $DB->getList($sql);
		
		$DB->beginTransaction();
		
		// 发送邮件
		$DB->setTransactionState(false);
		foreach ($friendList as $friend) {
			// 好友被分享的次数已满$G['max_share_box_times']
			if ($friend['last_be_shared_box_time'] >= $today && $friend['be_shared_box_times'] == 0) {
				return array(
					'val' => false,
					'msg' => $L['friend_be_shared_times_reached_max_today']
				);
			}
			$attach = array(
				array(
					'item_id'	=> $itemInfo['item_id'],
					'lvl'		=> $itemInfo['lvl'],
					'attr'		=> $itemInfo['attr']
				)
			);
			$content = $L['your_friend_share_box_to_you'];
			$ret = Mail::send(0, $friend, $content, 1, $attach);
		}
		$DB->setTransactionState(true);
		$now = time();
		
		// 更新分享次数和时间
		if ($ret) {
			if ($todayFirst) {
				$sql = 'UPDATE user set share_box_times='.($G['max_share_box_times']-1)
						.',last_share_box_time='.$now.' WHERE uid='.$uid;
			} else {
				$sql = 'UPDATE user set share_box_times=share_box_times-1,
							last_share_box_time='.$now.' WHERE uid='.$uid;
			}
			$ret = $DB->exeSql($sql);
		}
		
		// 更新好友被分享的次数和时间
		// 更新今天第一次被分享的好友数据
		if ($ret) {
			$sql = 'UPDATE user set be_shared_box_times='.($G['max_be_shared_box_times']-1)
					.', last_be_shared_box_time='.$now
					.' WHERE uid in ('.$friendIds.') and last_be_shared_box_time<'.$today;
			$ret = $DB->exeSql($sql);
			if ($ret !== false) $ret = true;
		}
		// 更新今天非第一次被分享的好友数据
		if ($ret) {
			$sql = 'UPDATE user set be_shared_box_times=be_shared_box_times-1, last_be_shared_box_time='
					.$now.' WHERE uid in ('.$friendIds.') and last_be_shared_box_time>='.$today;
			$DB->exeSql($sql);
			if ($ret !== false) $ret = true;
		}
		
		// 宝箱分享后仍然保留不消耗
		
		$result['val'] = (boolean)$ret;
		if ($ret) {
			$DB->commit();
		} else {
			$DB->rollBack();
			if (isset($result['msg'])) {
				$result['msg'] = $L['Failure_Update'];
			}
			$str = var_export($DB->errors, true);
			// 记录错误日志
			Log::save('treasurebox_share', $str);
		}
		
		return $result;
	}
	
	/**
	 * 获取宝箱分享的好友列表
	 * @param int $uid
	 */
	public static function getFriendList($uid)
	{
		global $DB, $L, $G;
		
		$today = strtotime('today');
		
		$list = Friend::getList($uid, 1);
		
		$friendIds = array();
		foreach ($list as $v) {
			$friendIds[] = $v['uid'];
		}
		$friendIds = join(',', $friendIds);
		
		$sql= 'SELECT uid,be_shared_box_times,last_be_shared_box_time FROM user '
				.' WHERE uid in ('.$friendIds.')';
		$tmp = $DB->getList($sql);
		
		$okList = array();
		foreach ($tmp as $v) {
			if ($v['last_be_shared_box_time'] < $today || $v['be_shared_box_times'] > 0) {
				$okList[] = $v['uid'];
			}
		}
		
		foreach ($list as $k=>$v) {
			if (in_array($v['uid'], $okList)) {
				$list[$k]['ok'] = true;
			} else {
				$list[$k]['ok'] = false;
			}
		}
		
		return $list;
	}
	
}










